<?php

namespace App\Http\Controllers\Api\Admin;

use Illuminate\Http\Request;
use App\Http\Requests\Api\Admin\AdminUserRequest;
use App\Http\Business\CaptchasBusiness;
use App\Http\Business\PowerBusiness;
use App\Models\Admin\AdminUsers;
use App\Models\Enum\Admin\AdminUserEnum;
use App\Models\Admin\AdminUsersIp;
use App\Models\Enum\Admin\AdminUserIpEnum;
use Illuminate\Support\Facades\Auth;
use App\Jobs\Api\SaveLastTokenJob;
use App\Http\Controllers\Api\Controller;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;

class AdminAuthController extends Controller
{
    protected $captchaBusiness;

    public function __construct()
    {
        $this->captchaBusiness = new CaptchasBusiness();
    }
    //用户注册
    public function store(AdminUserRequest $request){
        if (!$this->_checkCaptcha($request)){
            return $this->failed('用户注册失败');
        }
        $this->captchaBusiness->delCaptcha('admin');
        $user = [
            'name'=> $request->input('name'),
            'phone'=> $request->input('phone'),
            'password'=> $request->input('password'),
            'wechat'=> $request->input('wechat'),
            'qq'=> $request->input('qq'),
            'avatar' => 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
        ];

        AdminUsers::create($user);
        $this->captchaBusiness->delCaptcha('admin');
        return $this->setStatusCode(201)->success('用户注册成功');
    }
    //用户登录
    public function login(Request $request)
    {
        if (!$this->_checkCaptcha($request)){
            return $this->failed('用户登录失败');
        }
        //获取当前守护的名称
        $present_guard =Auth::getDefaultDriver();
        $token = Auth::claims(['guard'=>$present_guard])->attempt(['phone' => $request->phone, 'password' => $request->password]);
        if ($token) {
            $user = Auth::user();
            // 不允许用户登录逻辑: 不是超级管理员的用户冻结后禁止登录
            if (!PowerBusiness::isSuperAdmin($user->phone)){
                if($user->status==AdminUserEnum::INVALID||$user->status==AdminUserEnum::FREEZE){
                    $this->captchaBusiness->setCaptcha('admin');
                    return $this->failed('账号禁止登录', 400);
                }
            }
            if (!$this->_checkIp($request->getClientIp(), $user->user_id)){
                $this->captchaBusiness->setCaptcha('admin');
                return $this->failed('账号禁止该地登录', 400);
            }

            //如果登陆，先检查原先是否有存token，有的话先失效，然后再存入最新的token
            if ($user->last_token) {
                try{
                    Auth::setToken($user->last_token)->invalidate();
                }catch (TokenExpiredException $e){
                    //因为让一个过期的token再失效，会抛出异常，所以我们捕捉异常，不需要做任何处理
                }
            }

            SaveLastTokenJob::dispatch($user,$token);
            $this->captchaBusiness->delCaptcha('admin');
            return $this->setStatusCode(201)->success(['token' => 'bearer ' . $token]);
        }else{
            $this->captchaBusiness->setCaptcha('admin');
        }
        return $this->failed('账号或密码错误', 400);
    }
    //用户退出
    public function logout()
    {
        Auth::guard('admin')->logout();
        return $this->success('退出成功...');
    }


    /**
     * 记录用户的登录IP
     * @param $currentIp
     * @param $user_id
     * @return bool
     */
    protected function _checkIp($currentIp, $user_id)
    {
        $userIpModel = new AdminUsersIp();
        $map = [
          'ip' => $currentIp,
          'user_id' => $user_id
        ];
        $ipModel = $userIpModel->where($map)->first();
        if($ipModel){
            $ipModel->amount = $ipModel->amount + 1;
            $ipModel->save();
            if($ipModel->type == AdminUserIpEnum::FREEZE){
                return false;
            }
        }else{
          $userIpModel->create($map);
        }

        return true;
    }

    /**
     * 验证图片验证码
     * @param $request
     * @return bool
     */
    protected function _checkCaptcha($request)
    {
        $isCaptcha = $this->captchaBusiness->show();
        if ($isCaptcha){
            $captchaKey = $request->input('captcha_key');
            if (!$this->captchaBusiness->getVerifyRes($captchaKey)){
                return false;
            }
        }
        return true;
    }

}
